from fastapi import APIRouter, Request, HTTPException
from typing import Dict
from app.database import get_db
from app.models.marshall import MarshallTest, MarshallData
from sqlalchemy.orm import Session

router = APIRouter()

@router.post("/receive/marshall")
async def receive_marshall_data(request: Request, data: Dict):
    try:
        # 获取 source header
        source = request.headers.get("source")
        if not source:
            raise HTTPException(status_code=400, detail="Source header is required")

        # 获取数据库会话
        db = next(get_db())
        try:
            # 提取数据列表
            data_list = data.pop("dataList", [])
            
            # 创建主表记录
            test_data = {
                "source": source,
                "uuid": data["uuId"],
                "precative_num": data["precativeNum"],
                "equ_num": data["equNum"],
                "trial_date": data["trialDate"],
                "precative_date": data["precativeDate"],
                "report_num": data["reportNum"],
                "bridge_name": data["bridgeName"],
                "other_location": data.get("otherLocation"),
                "result": data["result"],
                "typical_value": data["typicalValue"],
                "typical_value2": data["typicalValue2"],
                "mxe_type": data["mxeType"],
                "road_level": data["roadLevel"],
                "traffic_type": data["trafficType"],
                "weather_region": data["weatherRegion"]
            }
            
            db_test = MarshallTest(**test_data)
            db.add(db_test)
            db.flush()  # 获取主表ID
            
            # 创建子表记录
            for item in data_list:
                db_data = MarshallData(
                    uuid=item["uuId"],
                    sample_id=item["sampleId"],
                    wdd=item["wdd"],
                    lz=item["lz"],
                    parent_id=item["parentId"],
                    test_id=db_test.id
                )
                db.add(db_data)
            
            db.commit()
            return {"code": 200, "message": "success"}
            
        except Exception as db_error:
            db.rollback()
            raise HTTPException(status_code=500, detail=f"Database error: {str(db_error)}")
        finally:
            db.close()
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 